// src/auth/wechat.service.ts
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../user/entity/user.entity';
import { GroupMap } from '../group/entity/group.entity';
import { wechatConstants } from '../../common/constant/wechat.constants';
import { JwtService } from '@nestjs/jwt';
import { nameVerify, passwordVerify } from 'src/common/tool/utils';
import { RCode } from 'src/common/constant/rcode';
import * as https from 'https';

interface WechatLoginResponse {
  openid: string;
  session_key: string;
  unionid?: string;
  errcode?: number;
  errmsg?: string;
}

@Injectable()
export class WechatService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(GroupMap)
    private readonly groupUserRepository: Repository<GroupMap>,
    private readonly jwtService: JwtService,
  ) {}

  // 使用https模块请求微信接口
  private async requestWechatAPI(url: string): Promise<any> {
    return new Promise((resolve, reject) => {
      https
        .get(url, res => {
          let data = '';

          res.on('data', chunk => {
            data += chunk;
          });

          res.on('end', () => {
            try {
              const result = JSON.parse(data);
              resolve(result);
            } catch (error) {
              reject(error);
            }
          });
        })
        .on('error', error => {
          reject(error);
        });
    });
  }

  // 获取微信openid
  async getWechatOpenid(code: string): Promise<WechatLoginResponse> {
    const { appId, appSecret } = wechatConstants;
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`;

    try {
      const result: WechatLoginResponse = await this.requestWechatAPI(url);

      if (result.errcode) {
        throw new HttpException(
          `微信登录失败: ${result.errmsg}`,
          HttpStatus.BAD_REQUEST,
        );
      }

      return result;
    } catch (error) {
      throw new HttpException(
        '微信服务请求失败',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  // 微信小程序登录
  async wechatLogin(body: { code: string }): Promise<any> {
    // 1. 获取openid
    const wechatResponse = await this.getWechatOpenid(body.code);
    const { openid } = wechatResponse;

    // 2. 查找用户
    let user = await this.userRepository.findOne({ where: { openid } });

    if (user) {
      // 用户已存在，直接登录
      const payload = { openid: user.openid };
      const friends = await this.groupUserRepository.find({
        where: { userId: user.userId },
      });

      console.log('登录成功', payload);
      return {
        msg: '微信登录成功',
        data: {
          user: {
            ...user,
            friends: friends ? friends : [],
          },
          token: this.jwtService.sign(payload),
          hasRegister: true,
        },
      };
    } else {
      // 3. 用户不存在，自动注册
      // return this.registerWechatUser(openid, body);
      return {
        msg: '请先注册用户',
        data: {
          user: null,
          token: null,
          openid: openid,
          hasRegister: false,
        },
      };
    }
  }

  // 注册微信用户
  async registerWechatUser(body: {
    openid: string;
    sex: string;
    birthday: string;
    mbti: string;
    avatar: string;
    username: string;
  }): Promise<any> {
    // 创建新用户
    const newUser = new User();
    newUser.role = 'user';
    newUser.openid = body.openid;
    newUser.sex = body.sex;
    newUser.birthday = body.birthday;
    newUser.mbti = body.mbti;
    newUser.avatar = body.avatar;
    newUser.username = body.username;

    try {
      const savedUser = await this.userRepository.save(newUser);
      const payload = {
        openid: savedUser.openid,
      };
      console.log('注册成功', payload);
      return {
        msg: '微信用户注册并登录成功',
        data: {
          user: {
            ...savedUser,
            friends: [],
          },
          token: this.jwtService.sign(payload),
        },
      };
    } catch (error) {
      return { code: RCode.FAIL, msg: '用户注册失败', data: error.message };
    }
  }

  // 绑定微信（用于已有账号绑定微信）
  async bindWechat(userId: string, code: string): Promise<any> {
    const wechatResponse = await this.getWechatOpenid(code);
    const { openid } = wechatResponse;

    // 检查openid是否已被绑定
    const existingUser = await this.userRepository.findOne({
      where: { openid },
    });
    if (existingUser) {
      return { code: RCode.FAIL, msg: '该微信已绑定其他账号', data: '' };
    }

    // 更新用户openid
    await this.userRepository.update({ userId }, { openid });

    return { msg: '微信绑定成功', data: '' };
  }

  // 解绑微信
  async unbindWechat(userId: string): Promise<any> {
    await this.userRepository.update({ userId }, { openid: '' });
    return { msg: '微信解绑成功', data: '' };
  }
}
